//
// Created by dddgzc on 2025/2/5.
//

#include "../include/SunBulletEx.h"

#include "SunBullet.h"

SunBulletEx::SunBulletEx() {
    size.x = 288;
    size.y = 288;

    damage = 20;

    animationIdle.setAtlas(sunExAtlas);
    animationIdle.setInterval(50);

    animationExExplode.setAtlas(sunExExplodeAtlas);
    animationExExplode.setInterval(50);
    animationExExplode.setIsLoop(false);
    animationExExplode.setOnAnimationFinishedCallback([&] {
        canRemove = true;
    });

    SDL_Texture *frameIdle = animationIdle.getFrame();
    SDL_Texture *frameExplode = animationExExplode.getFrame();
    int idleWidth, idleHeight, explodeWidth, explodeHeight;
    SDL_QueryTexture(frameIdle, NULL, NULL, &idleWidth, &idleHeight);
    SDL_QueryTexture(frameExplode, NULL, NULL, &explodeWidth, &explodeHeight);
    explodeRenderOffset.x = (float) (idleWidth - explodeWidth) / 2.0f;
    explodeRenderOffset.y = (float) (idleHeight - explodeHeight) / 2.0f;

}

void SunBulletEx::onCollide() {
    Bullet::onCollide();
    camera.shake(20, 500);
    // 播放爆炸音效
}

void SunBulletEx::onUpdate(int delta) {
    Bullet::onUpdate(delta);
    if (valid) {
        position += velocity * (float) delta;
    }

    if (!valid) {
        animationExExplode.onUpdate(delta);
    }else {
        animationIdle.onUpdate(delta);
    }

    if (checkIfExceedsScreen()) {
        canRemove = true;
    }

}

void SunBulletEx::onDraw(const Camera &camera) {
    Bullet::onDraw(camera);
    if (valid) {
        animationIdle.onDraw(camera, (int)position.x, (int)position.y);
    }else {
        animationExExplode.onDraw(camera, (int)(position.x + explodeRenderOffset.x), (int)(position.y + explodeRenderOffset.y));
    }
}

bool SunBulletEx::checkCollision(const Vector2 &position, const Vector2 &size) {
    bool isCollidedX = (std::max(this->position.x + this->size.x, position.x + size.x) - std::min(this->position.x, position.x) <= this->size.x + size.x);
    bool isCollidedY = (std::max(this->position.y + this->size.y, position.y + size.y) - std::min(this->position.y, position.y) <= this->size.y + size.y);
    return isCollidedX && isCollidedY;
}
